﻿using Colorful.Cache;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Colorful.CMS.Core
{
    /// <summary>
    /// CMS缓存服务
    /// </summary>
    public class CacheService
    {
        private ICacheService _cacheService;

        public CacheService(ICacheService cacheService)
        {
            _cacheService = cacheService;
        }

        #region 获取Key
        public string GetKey(string key)
        {
            if (key.StartsWith("#"))
                return key.Substring(1);
            var prefix = $"{System.Web.HttpContext.Current.GetUserId()}";
            if (!string.IsNullOrEmpty(prefix))
                key = $"{key}_{prefix}";
            return key;
        }
        #endregion

        #region 添加缓存
        public void Set<T>(string key, T data, TimeSpan? expiry = null)
        {
            key = this.GetKey(key);
            _cacheService.Set(key, data, expiry);
        }
        public Task<bool> SetAsync<T>(string key, T data, TimeSpan? expiry = null)
        {
            key = this.GetKey(key);
            return _cacheService.SetAsync(key, data, expiry);
        }
        #endregion

        #region 获取缓存
        public T Get<T>(string key)
        {
            key = this.GetKey(key);
            return _cacheService.Get<T>(key);
        }
        /// <summary>
        /// 获取缓存，如果缓存不存在则根据回调设置缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">存储缓存的键值（如果是全局缓存前面加#）</param>
        /// <param name="requireData">如果缓存不存在则根据回调设置缓存</param>
        /// <param name="expiry">过期时间</param>
        /// <returns></returns>
        public T Get<T>(string key, Func<T> requireData = null, TimeSpan? expiry = null)
        {
            key = this.GetKey(key);
            return _cacheService.Get(key, requireData, expiry);
        }
        public Task<T> GetAsync<T>(string key, Func<T> requireData = null, TimeSpan? expiry = null)
        {
            key = this.GetKey(key);
            return _cacheService.GetAsync<T>(key, requireData, expiry);
        }
        #endregion

        #region 移除缓存
        public void Remove(string key)
        {
            key = this.GetKey(key);
            _cacheService.Remove(key);
        }
        public Task<bool> RemoveAsync(string key)
        {
            return _cacheService.RemoveAsync(key);
        }
        #endregion
    }
}
